package com.epam.cdp.jpa.backingbeans;

import java.util.Map;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.epam.cdp.jpa.model.User;
import com.epam.cdp.jpa.services.LoginService;
import com.epam.cdp.jpa.utils.SessionAttributes;

@ManagedBean
@RequestScoped
public class LoginBackingBean {

    private static final Log log = LogFactory.getLog(LoginBackingBean.class);
    
    private String username;
    private String password;
    
    @EJB
    private LoginService loginService;
    
    public String login () {
	log.info("User " + username + " is trying to login.");
	User user = loginService.getUserByCredentials(username, password);
	if (user != null) {
	    log.info("User " + username + "has entered correct credentials and will be logged in.");
	    Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
	    sessionMap.put(SessionAttributes.USER.name(), user);
	    return "success";
	} else {
	    log.info("User " + username + " entered invalid credentials.");
	    // TODO pass proper error message to login page after login failed 
	    return "fail";
	}
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
}
